﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Batman.Cms.Core.Controllers;
using Batman.Cms.Core.Models.Mvc;
using Batman.Jianbei.Forum.Controllers.Posts.Converts;
using Batman.Jianbei.Forum.Controllers.Posts.Responses;
using Batman.Jianbei.Forum.Core.Consts;
using Batman.Jianbei.Forum.Core.Domains.Dicts;
using Batman.Jianbei.Forum.Core.Domains.Posts;
using Batman.Jianbei.Forum.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Controllers.Posts
{
    [Authorize]
    public class PostController : BatmanController<Post>
    {
        public IRepository<Topic, string> topicRepo { get; set; }

        public PostService PostService { get; set; }

        [Authorize]
        public ActionResult Create()
        {
            var name = User.Identity.Name;
            var claimsIdentity = User.Identities.FirstOrDefault(t => t.Name == UserClaims.UserId);
            if (claimsIdentity == null) return null;
            return null;
        }

        /// <summary>
        /// 微信H5端发布帖子
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        public async Task<ActionResult> WeixinH5Publish(WeixinH5PublishInput model)
        {
            var wxUserId = User.GetWxUserId();
            var result = await PostService.WeixinH5PublishAsync(model, wxUserId);
            return Json(result);
        }

        /// <summary>
        /// 获取帖子分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public IActionResult GetPosts(PagedResultRequestDto page)
        {
            var query = PostService.postRepo.GetAll().AsNoTracking().Include(t => t.WxUser).AsQueryable();

            query = query.Where(t => t.Status != Core.Enums.PostStatus.trashed);

            int total = query.Count();
            var items = query.OrderByDescending(t => t.CreateAt).Skip(page.SkipCount).Take(page.MaxResultCount)
                .Select(t => t.ToPostResponse()).ToList();

            var result = new PagedResultDto<PostResponse>(total, items);
            return Json(result);
        }

        /// <summary>
        /// 帖子放入回收站
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult Recycle(List<string> ids)
        {
            var reslut = BaseManager.Excute(repo =>
            {
                ids.ForEach(id => repo.Update(id, t => t.Status = Core.Enums.PostStatus.trashed));

                return new ResponseBase();
            });

            return Json(reslut);
        }
    }
}